package com.hanxiaozhang.validation.validator;


import com.hanxiaozhang.order.entity.Order;
import com.hanxiaozhang.util.BigDecimalUtil;
import com.hanxiaozhang.validation.annotation.PriceNotEmpty;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintViolationCreationContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;
import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 * 〈订单数量不为空时，价格不为零校验器〉
 *
 * @author hanxinghua
 * @create 2020/7/22
 * @since 1.0.0
 */
public class PriceNotEmptyValidator implements ConstraintValidator<PriceNotEmpty, BigDecimal> {



    @Override
    public void initialize(PriceNotEmpty priceNotEmpty) {

    }

    @Override
    public boolean isValid(BigDecimal price, ConstraintValidatorContext context) {

        ConstraintValidatorContextImpl constraintValidatorContext = (ConstraintValidatorContextImpl)context;
        List<ConstraintViolationCreationContext> constraintViolationCreationContexts = constraintValidatorContext.getConstraintViolationCreationContexts();
        ConstraintViolationCreationContext constraintViolationCreationContext = constraintViolationCreationContexts.get(0);
        Object object = constraintViolationCreationContext.getPath().getLeafNode().getParent().getValue();
        Order order = (Order) object;
        if (order == null) {
            return true;
        }
        // 数量大于0
        if (order.getNumber()>0) {
            // 价格大于0
            if (BigDecimalUtil.compare0(price)==1) {
                return true;
            }
        }

        return false;
    }

}
